package com.cljz.makepassenger.base;

import com.clzj.makepassenger.bean.UserInfo;
import com.clzj.makepassenger.dao.DaoSession;
import com.clzj.makepassenger.dao.UserInfoDao;
import com.google.gson.Gson;

import cn.droidlover.xdroidmvp.cache.SharedPref;
import cn.droidlover.xdroidmvp.mvp.IView;
import cn.droidlover.xdroidmvp.mvp.XPresent;
import de.greenrobot.dao.query.Query;

/**
 * Created by apple on 2017/4/5.
 */

public class BaseP<V extends IView> extends XPresent<V> {
    protected DaoSession daoSession = ((App) App.instance).getDaoSession();
    protected Gson gson;

    public BaseP() {
        gson = new Gson();
    }


    public UserInfo getLocalUserInfo(String token) {
        UserInfo userInfo = null;
        Query<UserInfo> query = daoSession.getUserInfoDao().queryBuilder()
                .where(UserInfoDao.Properties.Token.eq(token))
                .build();
        if (query.list().size() > 0) {
            userInfo = query.list().get(0);
        }
        return userInfo;
    }

    public String getToken() {
        return SharedPref.getInstance(App.getInstance()).getString(Constant.TOKEN, "");
    }

    /**
     * 用户信息存储到数据库
     *
     * @param userInfo 用户信息bean类
     */
    protected void updateDB(UserInfo userInfo) {
        if (getLocalUserInfo(getToken()) == null) {
            daoSession.getUserInfoDao().deleteAll();
            daoSession.getUserInfoDao().insert(userInfo);
        } else {
            daoSession.getUserInfoDao().update(userInfo);
        }
    }

}
